<template>
  <div class="sidebar">
    <div class="sidebar-header">
      <input type="text" class="search-input" placeholder="搜索好友ID或名称" v-model="searchKey">
      <button class="create-group-btn" @click="emitCreateGroup" v-if="isGroupMode">
        完成({{ selectedCount }})
      </button>
    </div>
    <ul class="friend-list">
      <!-- 新的朋友栏目 -->
      <li class="new-friends-item" @click="handleNewFriendsClick">
        <i class="fa fa-user-plus new-friends-icon"></i>
        <div class="new-friends-text">新的朋友</div>
        <span v-if="unreadRequests > 0" class="new-friends-badge">
          {{ unreadRequests }}
        </span>
      </li>
      
      <!-- 字母索引快速导航 -->
      <div class="alphabet-index" v-if="sortedLetters.length">
        <div 
          v-for="(letter) in sortedLetters" 
          :key="letter"
          class="alphabet-item"
          @click="scrollToLetter(letter)"
          :class="{ active: currentLetter === letter }"
        >
          {{ letter }}
        </div>
      </div>
      
      <!-- 按字母分组的好友列表 -->
      <template v-for="(letter) in sortedLetters" :key="letter">
        <!-- 字母分隔符 -->
        <li class="letter-divider" :id="`letter-${letter}`" ref="letterDividers">
          {{ letter }}
        </li>
        
        <!-- 该字母下的好友 -->
        <li v-for="(friend, index) in groupedFriends[letter]" :key="friend.id" class="friend-item"
          @click="handleFriendClick(friend)">
          <input type="checkbox" class="group-checkbox" v-if="isGroupMode" :checked="isSelected(friend.id)"
            @click.stop="handleCheckboxClick(friend)">
          <img :src="friend.avatarUrl || '/images/avatar-default.png'" alt="好友头像" class="friend-avatar"
            @error="() => friend.avatarUrl = '/images/avatar-default.png'">
          <div class="friend-info">
            <div class="friend-name">{{ friend.userName }}</div>
          </div>
        </li>
      </template>
      
      <!-- 无搜索结果时显示 -->
      <li class="no-result" v-if="!sortedLetters.length && searchKey">
        没有找到匹配的好友
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, defineEmits, onMounted, watch, nextTick, onUpdated } from 'vue';
import request from '../utils/request';

// 接收父组件参数
const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  isGroupMode: {
    type: Boolean,
    default: false
  },
  unreadRequests: {
    type: Number,
    default: 0
  }
});

// 定义事件
const emit = defineEmits(['select-friend', 'load-messages', 'create-group', 'enter-new-friends']);

// 状态管理
const friendList = ref([]);
const searchKey = ref('');
const selectedFriendIds = ref([]);
const isLoading = ref(false);
const letterDividers = ref([]);
const currentLetter = ref('');

// 监听选中的好友ID变化
watch(selectedFriendIds, (newVal) => {
  if (!Array.isArray(newVal)) {
    selectedFriendIds.value = [];
  }
});

// 组件挂载时加载好友列表
onMounted(async () => {
  await loadFriendList();
  setupScrollListener();
});

// 监听滚动，更新当前显示的字母
const setupScrollListener = () => {
  const friendListEl = document.querySelector('.friend-list');
  if (friendListEl) {
    friendListEl.addEventListener('scroll', updateCurrentLetterOnScroll);
  }
};

// 更新当前滚动到的字母
const updateCurrentLetterOnScroll = () => {
  if (!letterDividers.value.length) return;
  
  const scrollTop = document.querySelector('.friend-list').scrollTop;
  const current = letterDividers.value.find(divider => {
    const rect = divider.getBoundingClientRect();
    const friendListRect = document.querySelector('.friend-list').getBoundingClientRect();
    return rect.top >= friendListRect.top && rect.top <= friendListRect.top + 50;
  });
  
  if (current) {
    currentLetter.value = current.id.replace('letter-', '');
  }
};

// 组件更新后重新检查滚动位置
onUpdated(() => {
  nextTick(() => {
    updateCurrentLetterOnScroll();
  });
});

// 改进：使用字符映射表获取中文首字母（更精确）
const getFirstLetter = (str) => {
  if (!str || typeof str !== 'string' || str.trim() === '') {
    return '#';
  }
  
  const firstChar = str.trim().charAt(0);
  
  // 处理英文字母
  if (/[A-Za-z]/.test(firstChar)) {
    return firstChar.toUpperCase();
  }
  
  // 处理中文 - 使用字符直接映射表（覆盖常用字）
  if (/[\u4e00-\u9fa5]/.test(firstChar)) {
    // 中文字符拼音首字母映射表（常用字完整版）
    const pinyinMap = {
      'A': '吖啊阿呵嗄腌锕',
      'B': '八巴扒叭吧芭疤笆捌拔茇跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆浜榜膀绑棒磅蚌镑傍谤苞胞包褒雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表裱鳔憋鳖别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖',
      'C': '擦嚓猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措错',
      'D': '搭达答瘩打大呆歹傣戴带殆代贷袋待逮怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺',
      'E': '阿婀俄额讹娥恶厄扼遏鄂饿恩蒽儿而尔耳迩饵洱二贰',
      'F': '发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚',
      'G': '噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔个各给根跟更庚耕羹埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过',
      'H': '哈嗨骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活火伙或惑霍货祸',
      'J': '击圾基机畸稽积箕肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君',
      'K': '咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀馈愧溃坤昆捆困括扩廓阔',
      'L': '垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞麟凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘流柳六龙聋咙笼窿隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络',
      'M': '妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫谩芒茫盲氓忙莽猫茅锚毛矛卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆',
      'N': '拿镎哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟',
      'O': '哦喔鸥殴藕呕偶沤',
      'P': '啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑',
      'Q': '沏妻柒凄漆戚期欺栖其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀',
      'R': '然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹儒孺如辱乳汝入褥',
      'S': '撒洒萨腮鳃塞赛三叁伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松淞嵩怂耸颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁',
      'T': '塌他它她塔獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾',
      'W': '挖哇蛙洼瓦袜歪崴外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误',
      'X': '昔熙析西硒矽晰嘻吸锡牺稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙序畜恤絮婿绪续轩喧宣悬旋玄选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅',
      'Y': '压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶摇尧遥窑谣姚咬舀药要耀椰噎耶爷野也冶页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕',
      'Z': '匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正证政帧症郑支芝吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵'
    };
    
    // 遍历查找首字母
    for (const [letter, chars] of Object.entries(pinyinMap)) {
      if (chars.includes(firstChar)) {
        // 特别针对"嘻"字做验证
        if (firstChar === '嘻') {
          console.log('"嘻"字识别为X');
        }
        return letter;
      }
    }
    
    // 如果没找到，记录未识别的字符并返回#
    console.log(`未识别的中文字符: ${firstChar} (${firstChar.charCodeAt(0)})`);
    return '#';
  }
  
  // 其他字符（数字、符号等）归类到#
  return '#';
};

// 加载好友列表数据
const loadFriendList = async () => {
  try {
    isLoading.value = true;
    const res = await request.get('/user/getfriendlist', {
      params: {
        userId: props.userId
      }
    });
    let friends = res.data.data || [];

    // 为每个好友添加首字母属性
    friends = friends.map(friend => {
      const firstLetter = getFirstLetter(friend.userName || '');
      // 调试信息
      console.log(`好友: ${friend.userName}, 首字母: ${firstLetter}`);
      return {
        ...friend,
        firstLetter
      };
    });

    friendList.value = friends;
  } catch (err) {
    console.error('获取好友列表失败', err);
  } finally {
    isLoading.value = false;
  }
};

// 搜索过滤好友
const filteredFriends = computed(() => {
  const key = searchKey.value.trim().toLowerCase();
  if (!key) return friendList.value;
  return friendList.value.filter(friend =>
    (friend.userName && friend.userName.toLowerCase().includes(key)) ||
    (friend.id && friend.id.toString().includes(key))
  );
});

// 按首字母分组好友
const groupedFriends = computed(() => {
  return filteredFriends.value.reduce((groups, friend) => {
    const letter = friend.firstLetter;
    if (!groups[letter]) {
      groups[letter] = [];
    }
    groups[letter].push(friend);
    return groups;
  }, {});
});

// 对字母进行排序，确保#在最后
const sortedLetters = computed(() => {
  const letters = Object.keys(groupedFriends.value);
  // 分离#和其他字母
  const others = letters.filter(letter => letter !== '#').sort();
  const hasHash = letters.includes('#');
  
  // 如果有#，则放在最后
  return hasHash ? [...others, '#'] : others;
});

// 检查好友是否被选中
const isSelected = (friendId) => {
  return selectedFriendIds.value.includes(friendId);
};

// 计算选中的好友数量
const selectedCount = computed(() => selectedFriendIds.value.length);

// 好友点击事件
const handleFriendClick = async (friend) => {
  if (props.isGroupMode) {
    const currentIndex = selectedFriendIds.value.indexOf(friend.id);
    if (currentIndex !== -1) {
      selectedFriendIds.value.splice(currentIndex, 1);
    } else {
      selectedFriendIds.value.push(friend.id);
    }
  } else {
    try {
      const res = await request.get('/user/getfrienddialogue', {
        params: {
          userId: props.userId,
          friendId: friend.id
        }
      });
      const dialogueId = res.data.data;
      const contact = {
        id: dialogueId,
        name: friend.userName,
        avatar: friend.avatarUrl || '/images/avatar-default.png',
        isGroup: false,
        dialogueId: dialogueId,
        users: [friend]
      };
      emit('select-friend', contact);
      emit('load-messages', dialogueId);
    } catch (err) {
      console.error('获取会话ID失败', err);
    }
  }
};

// 复选框点击事件
const handleCheckboxClick = (friend) => {
  handleFriendClick(friend);
};

// 群聊模式下完成创建
const emitCreateGroup = () => {
  emit('create-group', selectedFriendIds.value);
};

// 点击"新的朋友"时处理
const handleNewFriendsClick = () => {
  emit('enter-new-friends');
  // 延迟确保视图切换完成
  setTimeout(() => {
    if (props.isGroupMode) {
      // 退出群聊模式
      selectedFriendIds.value = [];
    }
  }, 100);
};

// 滚动到指定字母分组
const scrollToLetter = (letter) => {
  nextTick(() => {
    const element = document.getElementById(`letter-${letter}`);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start' });
      currentLetter.value = letter;
    }
  });
};

// 暴露刷新好友列表的方法
defineExpose({
  refreshFriendList: loadFriendList
});
</script>

<style scoped>
/* 保持原有样式不变 */
.sidebar {
  width: 280px;
  height: 100vh;
  border-right: 1px solid #c7b7b7;
  display: flex;
  flex-direction: column;
  background-color: rgba(255, 255, 255, 0.7);
  position: relative;
}

.sidebar-header {
  padding: 12px;
  border-bottom: 1px solid rgba(255, 246, 246, 0.7);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search-input {
  width: calc(100% - 100px);
  height: 36px;
  border-radius: 18px;
  border: 1px solid rgba(229, 218, 218, 0.6);
  padding: 0 15px;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
  background-color: rgba(255, 255, 255, 0.6);
}

.friend-list {
  list-style: none;
  margin: 0;
  padding: 0;
  flex: 1;
  overflow-y: auto;
}

.new-friends-item {
  display: flex;
  align-items: center;
  padding: 15px 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  background-color: #f9f9f9;
}

.new-friends-icon {
  font-size: 18px;
  color: #07c160;
  margin-left: 5px;
}

.new-friends-text {
  margin-left: 15px;
  font-size: 16px;
  color: #333;
}

.new-friends-badge {
  margin-left: auto;
  margin-right: 10px;
  background-color: #ff0000;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 15px 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.7);
  cursor: pointer;
  transition: background-color 0.2s;
  padding-left: 15px;
}

.friend-item:hover {
  background-color: rgba(255, 255, 255, 0.7);
}

.friend-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  object-fit: cover;
}

.friend-info {
  margin-left: 15px;
  flex: 1;
}

.friend-name {
  font-size: 16px;
  color: rgba(51, 51, 51, 0.7);
}

.friend-list::-webkit-scrollbar {
  width: 6px;
}

.friend-list::-webkit-scrollbar-track {
  background: rgba(245, 245, 245, 0.6);
}

.friend-list::-webkit-scrollbar-thumb {
  background: rgba(221, 221, 221, 0.6);
  border-radius: 3px;
}

.friend-list::-webkit-scrollbar-thumb:hover {
  background: rgba(204, 204, 204, 0.7);
}

.create-group-btn {
  padding: 6px 12px;
  background-color: #07c160;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.group-checkbox {
  width: 18px;
  height: 18px;
  margin-right: 10px;
  cursor: pointer;
}

/* 字母分组相关样式 */
.letter-divider {
  padding: 5px 15px;
  background-color: #f0f0f0;
  color: #666;
  font-size: 14px;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.alphabet-index {
  position: fixed;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 10;
}

.alphabet-item {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #666;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.2s;
}

.alphabet-item:hover, .alphabet-item.active {
  background-color: #07c160;
  color: white;
}

.no-result {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>
